package request

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

var Request *http.Request

func IsPost() bool {
	return Request.Method == "POST"
}
func IsGet() bool {
	return Request.Method == "GET"
}

func GetPost() map[string]interface{} {
	contentType := Request.Header.Get("Content-Type")
	var from = make(map[string]interface{})
	if contentType == "application/json" {
		body, _ := ioutil.ReadAll(Request.Body)
		err := json.Unmarshal(body, &from)
		if err != nil {
			return from
		}
	}
	if contentType == "application/x-www-form-urlencoded" {
		body, err := ioutil.ReadAll(Request.Body)
		if err != nil {
			return from
		}
		params, err := url.QueryUnescape(string(body))
		if err != nil {
			return from
		}
		stringArr := strings.Split(params, "&")
		if len(stringArr) <= 0 {
			return from
		}
		for _, val := range stringArr {
			arr := strings.Split(val, "=")
			from[arr[0]] = arr[1]
		}
	} else {
		err := Request.ParseMultipartForm(32 << 20)
		if err != nil {
			return from
		}
		if len(Request.MultipartForm.Value) <= 0 {
			return from
		}
		maps := Request.MultipartForm.Value
		for key, val := range maps {
			from[key] = val[0]
		}
	}


	return from
}

